<template>
  <div class="template navigation-container">
    <div class="title">导航</div>
    <div class="content">
      <div class="block">
        <div class="dt">规格</div>
        <div class="dd" v-if="!isScroll">
          <el-input v-model="x" placeholder="输入列数" @change="onChangeX">
            <template slot="append">列</template>
          </el-input>
          <div class="lock">
            <i class="el-icon-close"/>
          </div>
          <el-input v-model="y" placeholder="输入行数" @change="onChangeY">
            <template slot="append">行</template>
          </el-input>
        </div>
        <div class="dd">
          <div class="switch-item">
            <div class="switch-item-label">
              是否显示文字
            </div>
            <el-switch
              :value="isShowText"
              active-color="#13ce66"
              inactive-color="#ff4949"
              @change="onChangeShowText"
            >
            </el-switch>
          </div>
        </div>
        <div class="dd">
          <div class="switch-item">
            <div class="switch-item-label">
              是否显示图片
            </div>
            <el-switch
              :value="isShowImg"
              disabled
              active-color="#13ce66"
              inactive-color="#ff4949"
              @change="onChangeShowImg"
            >
            </el-switch>
          </div>
        </div>
      </div>
      <panel-common />
      <div class="block">
        <div class="dt">内容
          <el-button type="text" @click="addElement">新增</el-button>
        </div>
        <div class="list">
          <ul class="grid-content-ul">
            <!-- <li class="content-li">
              <el-button icon="el-icon-plus" plain @click="addElement"></el-button>
            </li> -->
            <li v-for="(item, index) of list" :key="index" @click="editHandle(item, index)" class="content-li">
              <el-image :src="item.url" fit="contain">
                <div slot="error" class="image-slot">
                  <i class="el-icon-picture-outline" />
                </div>
              </el-image>
              <div class="delete" @click.stop="deleteElement(item, index)">
                <i class="el-icon-delete" />
              </div>
            </li>
          </ul>
        </div>
        <div class="tips">请使用<em>宽120~200像素</em>-<em>高120~200像素</em>内的<em>jpg</em>或<em>png</em>透明<em>正方形</em>图片, 根据规格排列选择尺寸</div>
      </div>
      <div class="block" v-if="isEdit">
        <div class="dt">编辑{{showEditInfo}}</div>
        <div class="dd">
          <el-form ref="form" :model="form" label-width="80px">
            <!-- <el-form-item label="图片">
              <upload @on-success="imgUpdateSuccessHandle">
                <el-image v-if="form.url" :src="form.url" fit="contain" />
                <i v-else class="el-icon-plus"></i>
              </upload>
            </el-form-item> -->
            <el-form-item>
              <template #label>
                <upload @on-success="imgUpdateSuccessHandle">
                  <el-image v-if="form.url" :src="form.url" fit="contain" />
                  <el-button v-else class="button-upload" icon="el-icon-plus" plain></el-button>
                </upload>
              </template>
              <el-input v-model="form.name" placeholder="名称 推荐长度2~4" maxlength="4" show-word-limit />
            </el-form-item>
            <!-- <el-form-item label="开始时间">
              <el-date-picker v-model="form.startDate" value-format="yyyy-MM-dd" />
            </el-form-item>
            <el-form-item label="结束时间">
              <el-date-picker v-model="form.endDate" value-format="yyyy-MM-dd" />
            </el-form-item> -->
            <el-form-item label="跳转类型">
              <el-select v-model="form.targetType" placeholder="请选择跳转类型">
                <el-option label="不跳转" value="0" />
                <el-option label="商品" value="1" />
                <el-option label="活动" value="2" />
                <el-option label="资讯" value="3" />
              </el-select>
            </el-form-item>
            <el-form-item label="跳转链接">
              <el-input v-model="form.link" />
            </el-form-item>
            <el-form-item label="跳转编号">
              <el-input v-model="form.targetParams" />
            </el-form-item>
          </el-form>
        </div>
        <div class="submit">
          <el-button type="primary" @click="onSubmit">确定</el-button>
        </div>
      </div>
    </div>
  </div>
</template>

<script>
import { mapState } from 'vuex'
import { STORE_NAMESPACE } from '../../../../config'
import { uuid } from '../../../../common/'
import Upload from '../../../upload'
import PanelCommon from '../common'
export default {
  name: 'PanelNavigation',
  components: {
    Upload,
    PanelCommon
  },
  data () {
    return {
      x: 0,
      y: 0,
      currentElement: null,
      currentElementIndex: null,
      form: {
        link: '',
        name: '',
        url: '',
        // startDate: '',
        // endDate: '',
        targetType: '',
        targetParams: ''
      },
      fileInfo: null,
      formHistoryData: {}
    }
  },
  computed: {
    ...mapState({
      current: state => state[STORE_NAMESPACE].current || {},
      currentIndex: state => state[STORE_NAMESPACE].currentIndex,
      shopId: state => state[STORE_NAMESPACE].shopId
    }),
    column () {
      return this.current.column * 1
    },
    row () {
      return this.current.row * 1
    },
    isScroll () {
      return this.current.type === 'scroll'
    },
    list () {
      return this.current.elements
    },
    isEdit () {
      return this.currentElement
    },
    showEditInfo () {
      return this.currentElementIndex === null ? '(新增)' : `(第${this.currentElementIndex + 1}张)`
    },
    isShowText () {
      return this.current.isShowText
    },
    isShowImg () {
      return this.current.isShowImg
    }
  },
  watch: {
    'column': {
      handler (val) {
        this.x = this.column
      },
      immediate: true
    },
    'row': {
      handler (val) {
        this.y = this.row
      },
      immediate: true
    },
    'current.uuid' (currentId, oldId) {
      Object.keys(this.form).map(key => (this.form[key] = '')) // 目前切换的时候直接清除就可以了
      // this.formHistoryData[oldId] = { ...this.form }
      // this.formHistoryData[currentId] ? 
      //   (this.form = { ...this.formHistoryData[currentId] }) :
      //   Object.keys(this.form).map(key => (this.form[key] = ''))
    }
  },
  methods: {
    onChangeX (val) {
      if (!/^[1-9]([0-9])*$/gi.test(val)) {
        this.$message.warning('列数仅支持输入正整数')
        this.x = this.column
        return
      }
      const x = Number(val)
      if (x < 2) {
        return this.$message.warning('列数最小为2')
      }
      this.$store.dispatch(`${STORE_NAMESPACE}/setData`, {
        type: 'update',
        index: this.currentIndex,
        value: {
          ...this.current,
          column: x,
          row: this.y,
          // elements: this.calcElements(this.current.elements, x, this.y)
        }
      })
    },
    onChangeY (val) {
      if (!/^[1-9]([0-9])*$/gi.test(val)) {
        this.$message.warning('行数仅支持输入正整数')
        this.y = this.row
        return
      }
      const y = Number(val)
      this.y = y
      this.$store.dispatch(`${STORE_NAMESPACE}/setData`, {
        type: 'update',
        index: this.currentIndex,
        value: {
          ...this.current,
          column: this.x,
          row: y,
          // elements: this.calcElements(this.current.elements, this.x, y)
        }
      }).then(() => {
        // 重新设置current数据
        this.$store.dispatch(`${STORE_NAMESPACE}/setCurrent`, this.$store.state[STORE_NAMESPACE].layouts[this.$store.state[STORE_NAMESPACE].currentIndex])
      })
    },
    onChangeShowText (val) {
      console.log(val)
      this.$store.dispatch(`${STORE_NAMESPACE}/setData`, {
        type: 'update',
        index: this.currentIndex,
        value: {
          ...this.current,
          isShowText: !this.isShowText
        }
      })
    },
    onChangeShowImg (val) {
      console.log(val)
      this.$store.dispatch(`${STORE_NAMESPACE}/setData`, {
        type: 'update',
        index: this.currentIndex,
        value: {
          ...this.current,
          isShowImg: !this.isShowImg
        }
      })
    },
    calcElements (elements, x, y) {
      const oldLength = elements.length
      const nowLength = x * y
      const column = nowLength - oldLength
      if (column <= 0) {
        return elements.slice(0, nowLength)
      }
      return [
        ...elements,
        ...new Array(column).fill(null).map(() => ({
          targetType: '0',
          targetParams: '', // 跳转参数
          // startData: '', // 开始时间
          // endDate: '', // 结束时间
          name: '', // 菜单名
          url: '', // 图片地址
          link: '' // 跳转链接
        }))
      ]
    },
    editHandle (item, index) {
      console.log(item, index)
      this.currentElement = { ...item }
      this.currentElementIndex = index
      this.form = { ...item }
    },
    imgUpdateSuccessHandle (file) {
      console.log('文件修改: ', file)
      this.fileInfo = { ...file } // 注意form的name为当前菜单名, 不取file的name值
      this.form.url = file.url
    },
    addElement () {
      this.currentElementIndex = null
      this.currentElement = {}
      this.form = {
        link: '',
        name: '',
        url: '',
        // startDate: '',
        // endDate: '',
        targetType: '',
        targetParams: ''
      }
    },
    deleteElement (item, index) {
      console.log(item, index)
      this.setElement('delete', null, index)
    },
    onSubmit () {
      const index = this.currentElementIndex
      const type = index === null ? 'push' : 'update'
      const value = this.form
      this.setElement(type, value, index)
    },
    setElement (type = 'push', form = null, index = null) {
      this.$store.dispatch(`${STORE_NAMESPACE}/setElement`, {
        type,
        index,
        value: form && {
          link: form.link,
          name: form.name,
          url: form.url,
          uuid: uuid(this.shopId, 'image'),
          width: this.fileInfo ? this.fileInfo.width : '',
          height: this.fileInfo ? this.fileInfo.height : '',
          // startDate: form.startDate,
          // endDate: form.endDate,
          targetType: form.targetType,
          targetParams: form.targetParams
        }
      }).then(() => {
        if (type === 'push') {
          this.currentElementIndex = this.list.length - 1
        }
        if (type === 'delete') {
          this.currentElement = null
          this.currentElementIndex = null
          if (this.list.length === 0) {
            this.$store.dispatch(`${STORE_NAMESPACE}/setData`, {
              type: 'delete',
              index: this.currentIndex
            })
            this.$store.dispatch(`${STORE_NAMESPACE}/setCurrent`, null)
            this.$store.dispatch(`${STORE_NAMESPACE}/setCurrentIndex`, null)
          }
        }
      })
    },
  }
}
</script>

<style lang="less" scoped>
.navigation-container {
  .lock {
    display: flex;
    align-items: center;
    padding: 0 25px;
    i {
      font-size: 15px;
      color: #909399;
    }
  }
  .dt {
    .el-button {
      float: right;
      overflow: hidden;
      padding: 0;
    }
    &:after {
      clear: both;
    }
  }
  .dd {
    .el-image {
      width: 40px;
      height: 40px;
      line-height: 40px;
      overflow: unset;
      display: inherit;
      ::v-deep .el-image__error {
        display: none;
      }
    }
    ::v-deep .el-form-item,
    ::v-deep .el-form-item__content {
      height: 40px;
      i {
        font-size: 15px;
        color: #909399;
      }
    }
    .button-upload {
      width: 40px;
      height: 40px;
      padding: 0;
    }
  }
  .grid-content-ul {
    display: grid !important;
    grid-template-columns: repeat(auto-fill, 80px) !important;
    grid-template-rows: 80px !important;
    margin: auto !important;
    grid-gap: 5px 5px !important;
  }
  .content-li {
    position: relative;
    background: #fbfbfb;
    border: 1px dashed #c0ccda;
    box-sizing: border-box;
    border-radius: 6px;
    &:hover {
      .delete {
        display: flex;
      }
    }
    .el-button {
      border: unset;
      width: 100%;
      height: 100%;
    }
  }
  .delete {
    display: none;
    position: absolute;
    width: 20px;
    height: 20px;
    top: 0;
    right: 0;
    justify-content: center;
    align-items: center;
    z-index: 1000;
    cursor: pointer;
    i {
      font-size: 17px;
      color: #f4516c;
    }
  }
}
</style>